package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyServiceImpl implements IStrategyService {


    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private StrategyThemeServiceImpl strategyThemeService;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate mongoTemplate;


    // 那个没有值要给上值
    // 根据已经有的东西找到需要有的东西
    @Override
    public void save(Strategy strategy) {
//        strategy.setId(null);
        StrategyCatalog strategyCatalog = strategyCatalogService.get(strategy.getCatalogId());
        // 从分类对象中找到目的地的id
        strategy.setDestId(strategyCatalog.getDestId());
        // 从分类对象中找到目的地的name
        strategy.setDestName(strategyCatalog.getDestName());
        // 主题名字
        strategy.setCatalogName(strategyCatalog.getName());
        // 根据主题Id找到主题名字
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());
        // 当新增时才设置时间
        if (!StringUtils.hasLength(strategy.getId())) {
            // 发布时间
            strategy.setCreateTime(new Date());
        }
        // 国内还是国外
        if (StringUtils.hasLength(strategyCatalog.getDestId())){
            // 根据分类对象的目的地id  找到所有目的地的上级对象
            List<Destination> toasts = destinationService.gettoasts(strategyCatalog.getDestId());
            // 不包含中国就是国外
            if (!(toasts.get(0).getName()).equals("中国")){
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }else{
                // 含中国就是国内
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }
        }
        strategyRepository.save(strategy);
    }

    /**
     * 如果把save和update方法分开写  就要写两遍设置属性
     * @param strategy
     */
    @Override
    public void update(Strategy strategy) {

        StrategyCatalog strategyCatalog = strategyCatalogService.get(strategy.getCatalogId());
        // 从分类对象中找到目的地的id
        strategy.setDestId(strategyCatalog.getDestId());
        // 从分类对象中找到目的地的name
        strategy.setDestName(strategyCatalog.getDestName());
        // 主题名字
        strategy.setCatalogName(strategyCatalog.getName());
        // 根据主题Id找到主题名字
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());

        // new 一个Query
        Query query = new Query();

        // 修改的条件
        query.addCriteria(Criteria.where("_id").is(strategy.getId()));
        // 传上去要改的内容(工具类)
        DBHelper.update(mongoTemplate,query,strategy,"destId","destName","themeId",
                                                               "themeName","catalogId","catalogName",
                                                               "title","subTitle","summary",
                                                                "coverUrl","isabroad","state","content"

        );

}

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);

    }

    @Override
    public Strategy get(String id) {
        Optional<Strategy> op = strategyRepository.findById(id);
        if (op.isPresent()){
            Strategy strategy = op.get();
            return strategy;
        }
        return null;
    }

    @Override
    public List<Strategy> list()
    {
        return strategyRepository.findAll();
    }

    // 分页操作
    @Override
    public Page<Strategy> query(StrategyQuery qo) {

        Query query = new Query();
        // 查询总页数
        long count = mongoTemplate.count(query, Strategy.class);
        if (count == 0){
            return Page.empty();
        }

        /**
         * 条件
         */
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        // 分页排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<Strategy> list = mongoTemplate.find(query, Strategy.class);


        return new PageImpl<>(list,pageable,count);

    }


    /**
     * 根据目的地分类概括id找寻攻略明细
     * @param id
     * @return
     */
    @Override
    public List<Strategy> queryCatalogsByCatalogId(String id) {

        List<Strategy> strategies = strategyRepository.findByCatalogId(id);
        return strategies;
    }

    /**
     * 目的地下点击量前3的攻略
     * @param destId
     * @return
     */
    @Override
    public List<Strategy> queryViewNumTop3(String destId) {
        // 只拿点击量前三的数据
        Pageable pageable = PageRequest.of(0,3,Sort.Direction.DESC,"Viewnum");

        //  通过目的地Id在攻略明细中找
        List<Strategy> strategies = strategyRepository.findByDestId(destId,pageable);
        return strategies;
    }

    /**
     * redis数据持久化到mongdb中
     * @param vo
     */
    @Override
    public void updateStrategy(StrategyStatisVO vo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        Update update = new Update();
        update.set("viewnum",vo.getViewnum());
        update.set("replynum",vo.getReplynum());
        update.set("favornum",vo.getFavornum());
        update.set("sharenum",vo.getSharenum());
        update.set("thumbsupnum",vo.getThumbsupnum());
        mongoTemplate.updateMulti(query,update,Strategy.class);

    }

    @Override
    public List<Strategy> findByDestName(String name) {
        return strategyRepository.findByDestName(name);
    }


}
